import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    addlist: localStorage.addlist ? JSON.parse(localStorage.addlist) : []
  },
  getters: {
    checked(state) {
      return state.addlist.every(item => item.check)
    },
    getprice(state) {
      let total = 0;
      state.addlist.forEach(item => {
        if (item.check) {
          total += item.num * item.price * 100;
        }
      })
      return total;
    }
  },
  mutations: {
    Save(state, payloud) {
      console.log(payloud);
      let index = state.addlist.findIndex(item => item.id == payloud.id);
      if (index == -1) {
        state.addlist.push(payloud)
      } else {
        state.addlist[index].num++;
      }
      localStorage.addlist = JSON.stringify(state.addlist)
    },
    Savedel(state, payloud) {
      let index = state.addlist.findIndex(item => item.id == payloud.id);
      state.addlist.splice(index, 1)
      localStorage.addlist = JSON.stringify(state.addlist)
    },
    Savvechen(state, payloud) {
      state.addlist.forEach(item => {
        item.check = payloud.checked;
      })
      localStorage.addlist = JSON.stringify(state.addlist)
    }
  },
  actions: {
  },
  modules: {
  }
})
